const { spawn } = require('child_process')
const fs = require('fs')
class Daemon {
    constructor() {
    }
    /**
     * 初始化线程
     * @param {*} config 
     */
    async init(routes, Logger) {
        /**初始化 logger **/
        this.Logger = Logger
        await this.multi(routes)
    }

    /**
     * 开启子进程
     * @param {array} routes 
     */
    async multi(routes) {
        for (let route of routes) {
            await this.handle(route)
        }
    }

    /**
     * 开启子进程
     * @param {array} route 
     */
    async handle(route) {
        const ls = spawn(route['command'], route['args'], route['options'])
        
        await this.Logger.log(`子进程开启，启动文件：${route['args'][0]} PID: ${ls.pid} `)
        ls.stdout.on('data', async (data) => {
            await this.Logger.log(data.toString('utf8'))
        });

        ls.stderr.on('data', async (data) => {
            await this.Logger.log(data.toString('utf8'))
        });
        ls.on('close',async (code) => {
            await this.Logger.log(`子进程关闭：${code}`)
            await this.handle(route)
        });
    }
    async logPid () {
    
    }
}

module.exports = new Daemon()